<?php
namespace App\Admin\Controllers\File;

use App\Admin\Ajax\File\ParseOperationFileAjax;
use App\Models\Basics\AmazonCountry;
use App\Models\File\FileOperation;
use App\Admin\Actions\File\Operation\ParseFile;
use App\Admin\Actions\File\Operation\ImportFile;
use App\Util\User;
use Encore\Admin\Admin;
use Encore\Admin\Controllers\AdminController;
use Encore\Admin\Form;
use Encore\Admin\Grid;
class OperationController extends AdminController{

    protected $title = '运营文件管理';

    protected function grid()
    {
        Admin::script($this->_script());
        $grid = new Grid(new FileOperation());
        $grid->model()->orderBy('id', 'DESC');
        $grid->column('id','ID');
        $grid->column('country.country','国家');
        $grid->column('file_date','文件日期')->display(function ($value){
            return date('Y.m.d',strtotime($value));
        });
        $grid->column('file_type','文件类型')->using(FileOperation::$_fileType);
        $grid->column('file_name','文件名');
        $grid->column('status','状态')->using(FileOperation::$_status)->filter(FileOperation::$_status);
        $grid->column('user_id','操作人')->display(function ($value){
            return User::getUsernameById($value);
        });
        $grid->column('updated_at','操作时间')->sortable();
        $grid->column('操作')->view('file.operation.action');
        $grid->tools(function (Grid\Tools $tools) {
            $tools->append(new ImportFile());
            $tools->append(new ParseFile());
        });
        $grid->disableActions();
        $grid->disableExport();
        $grid->disableCreateButton();
        $grid->filter(function($filter){
            $filter->column(1/3, function ($filter) {
                $filter->equal('country_id','国家')->select(AmazonCountry::options());
            });
            $filter->column(1/3, function ($filter) {
                $filter->equal('file_type','类型')->select(FileOperation::$_fileType);
            });
            $filter->column(1/3, function ($filter) {
                $filter->between('file_date', '日期')->datetime();
            });
        });
        return $grid;
    }

    protected function _script()
    {
        $token = csrf_token();
        return <<<EOT
$('.grid-row-delete').unbind('click').click(function() {
    var id = $(this).data('id');
    swal({
        title: "确认删除?",
        type: "warning",
        showCancelButton: true,
        confirmButtonColor: "#DD6B55",
        confirmButtonText: "确认",
        showLoaderOnConfirm: true,
        cancelButtonText: "取消",
        preConfirm: function() {
            return new Promise(function(resolve) {
                $.ajax({
                    method: 'post',
                    url: '/xqc/file/operation/' + id,
                    data: {
                        _method:'delete',
                        _token: "{$token}",
                    },
                    success: function (data) {
                        resolve(data);
                    }
                });
            });
        }
    }).then(function(result) {
        var data = result.value;
        if (typeof data === 'object') {
            if (data.status) {
                $.pjax.reload('#pjax-container');
                toastr.success('删除成功 !');
            } else {
                swal(data.message, '', 'error');
            }
        }
    });
});
EOT;
    }

    protected function download()
    {
        $id = request('id');
        $f = FileOperation::query()->find($id);
        if(!$f) {
            admin_toastr('无文件记录！','error');
            return back();
        }
        try{
            $fileDir = FileOperation::fileDir(strtotime($f->file_date));
            $fileName = FileOperation::fileName($f->country_id,$f->file_type,$f->user_id,$f->file_name);
            $file = public_uploads_path($fileDir).DIRECTORY_SEPARATOR.$fileName;
            if(!file_exists($file)){
                admin_toastr('无文件！','error');
                return back();
            }
            return response()->download($file);
        }catch (\Exception $e){
            report($e);
            admin_toastr('操作失败！','error');
            return back();
        }
    }

    public function form()
    {
        return new Form(new FileOperation());
    }

    public function ajax(){
        $action = request('action');
        $param = request('param');
        $ajax = new ParseOperationFileAjax();
        return $param ? call_user_func([$ajax,$action],$param) : call_user_func([$ajax,$action]);
    }
}
